package com.meilai.project.controller.web.business.building;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.meilai.project.dto.CommonResult;
import com.meilai.project.dto.media.ImportAbPointDTO;
import com.meilai.project.dto.media.ImportCommonPointDTO;
import com.meilai.project.dto.media.MediaPointDTO;
import com.meilai.project.entity.media.MediaPoint;
import com.meilai.project.mapper.business.media.MediaPointMapper;
import com.meilai.project.mapper.business.media.MediaPointTypeSpecsRelationMapper;
import com.meilai.project.service.business.media.MediaPointService;
import com.meilai.project.util.ExcelUtils;
import com.meilai.project.vo.business.media.CommonPointListVO;
import com.meilai.project.vo.business.media.MediaDetailVO;
import com.meilai.project.vo.business.media.MediaPointVO;
import com.meilai.project.vo.business.media.SpecialPointListVO;
import io.swagger.annotations.*;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@Api(value = "点位管理", tags = {"点位管理"})
@RestController
@RequestMapping("api/web/media_point")
public class MediaPointController {

    @Autowired
    private MediaPointService service;

    @Autowired
    private MediaPointMapper mediaPointMapper;

    @Autowired
    private MediaPointTypeSpecsRelationMapper mediaPointTypeSpecsRelationMapper;

    @ApiOperation(value = "普通点位列表", notes = "普通点位列表", response = CommonPointListVO.class)
    @ApiResponses({@ApiResponse(code = CommonResult.SUCCESS, message = "操作成功"),
            @ApiResponse(code = CommonResult.VALIDATE_FAILED, message = "参数校验失败"),
            @ApiResponse(code = CommonResult.UNAUTHORIZED, message = "未认证"),
            @ApiResponse(code = CommonResult.FORBIDDEN, message = "未授权"),
            @ApiResponse(code = CommonResult.FAILED, message = "操作失败")})
    @ResponseBody
    @GetMapping("list")
    public CommonResult list(
            @ApiParam(name = "building_area_id", value = "项目id", required = false)
            @RequestParam(value = "building_area_id", required = false) Long building_area_id,
            @ApiParam(name = "code", value = "编号", required = false)
            @RequestParam(value = "code", required = false) String code) {

        MediaPointDTO searchDTO = new MediaPointDTO();
        searchDTO.setBuilding_area_id(building_area_id);
        searchDTO.setCode(code);

        return new CommonResult().success(service.selectList(searchDTO));
    }

    @ApiOperation(value = "特殊点位列表", notes = "特殊点位列表-楼宇/市场", response = SpecialPointListVO.class)
    @ApiResponses({@ApiResponse(code = CommonResult.SUCCESS, message = "操作成功"),
            @ApiResponse(code = CommonResult.VALIDATE_FAILED, message = "参数校验失败"),
            @ApiResponse(code = CommonResult.UNAUTHORIZED, message = "未认证"),
            @ApiResponse(code = CommonResult.FORBIDDEN, message = "未授权"),
            @ApiResponse(code = CommonResult.FAILED, message = "操作失败")})
    @ResponseBody
    @GetMapping("special_list")
    public CommonResult special_list(
            @ApiParam(name = "building_area_id", value = "项目id", required = false)
            @RequestParam(value = "building_area_id", required = false) Long building_area_id,
            @ApiParam(name = "building_type", value = "楼层类型：1、多层2、高层", required = false)
            @RequestParam(value = "building_type", required = false) Integer building_type,
            @ApiParam(name = "building_number", value = "楼号", required = false)
            @RequestParam(value = "building_number", required = false) String building_number,
            @ApiParam(name = "unit_number", value = "单元号", required = false)
            @RequestParam(value = "unit_number", required = false) String unit_number,
            @ApiParam(name = "floor", value = "楼层", required = false)
            @RequestParam(value = "floor", required = false) String floor,
            @ApiParam(name = "code", value = "编号", required = false)
            @RequestParam(value = "code", required = false) String code,
            @ApiParam(name = "ab_type_id", value = "AB面id", required = false)
            @RequestParam(value = "ab_type_id", required = false) Long ab_type_id,
            @ApiParam(name = "is_light", value = "是否亮灯", required = false)
            @RequestParam(value = "is_light", required = false) Boolean is_light) {

        MediaPointDTO searchDTO = new MediaPointDTO();
        searchDTO.setBuilding_area_id(building_area_id);
        searchDTO.setBuilding_type(building_type);
        searchDTO.setBuilding_number(building_number);
        searchDTO.setUnit_number(unit_number);
        searchDTO.setFloor(floor);
        searchDTO.setCode(code);
        searchDTO.setAb_type_id(ab_type_id);
        searchDTO.setIs_light(is_light);

        return new CommonResult().success(service.selectSpecialList(searchDTO));
    }

    @ApiOperation(value = "市场ab点位列表", notes = "市场ab点位列表")
    @ResponseBody
    @GetMapping("ab_pointList")
    public CommonResult ab_pointList(
            @ApiParam(name = "building_area_id", value = "项目id", required = false)
            @RequestParam(value = "building_area_id", required = false) Long building_area_id) {
        return new CommonResult().success(service.getABPointList(building_area_id));
    }

    @ApiOperation(value = "单点位详情", notes = "单点位详情", response = MediaPointVO.class)
    @ApiResponses({@ApiResponse(code = CommonResult.SUCCESS, message = "操作成功"),
            @ApiResponse(code = CommonResult.VALIDATE_FAILED, message = "参数校验失败"),
            @ApiResponse(code = CommonResult.UNAUTHORIZED, message = "未认证"),
            @ApiResponse(code = CommonResult.FORBIDDEN, message = "未授权"),
            @ApiResponse(code = CommonResult.FAILED, message = "操作失败")})
    @ResponseBody
    @GetMapping("detail/{id}")
    public CommonResult detail(@ApiParam(name = "id", value = "点位id", required = true) @PathVariable("id") Long id) {
        MediaDetailVO vo = new MediaDetailVO();
        MediaPoint md = service.getById(id);
        BeanUtils.copyProperties(md, vo);
        vo.setMedia_type_specs_id(md.getMedia_type_spec_id());
        return new CommonResult().success(vo);
    }


    @ApiOperation(value = "批量录入", notes = "批量录入")
    @ApiResponses({@ApiResponse(code = CommonResult.SUCCESS, message = "操作成功"),
            @ApiResponse(code = CommonResult.VALIDATE_FAILED, message = "参数校验失败"),
            @ApiResponse(code = CommonResult.UNAUTHORIZED, message = "未认证"),
            @ApiResponse(code = CommonResult.FORBIDDEN, message = "未授权"),
            @ApiResponse(code = CommonResult.FAILED, message = "操作失败")})
    @ResponseBody
    @PostMapping("save")
    public CommonResult save(@RequestBody @Valid @ApiParam(name = "传输对象", value = "传入json格式", required = true) List<MediaPointDTO> dto
            , BindingResult bindingResult) {
        if (bindingResult.hasErrors()) return new CommonResult().validateFailed(bindingResult);
        try {
            if (service.saveList(dto)) {
                return new CommonResult().success("新增成功");
            } else {
                return new CommonResult().failed("新增失败");
            }
        } catch (Exception e) {
            return new CommonResult().failed(e.getMessage());
        }
    }


    @ApiOperation(value = "注销点位", notes = "注销点位")
    @ApiResponses({@ApiResponse(code = CommonResult.SUCCESS, message = "操作成功"),
            @ApiResponse(code = CommonResult.VALIDATE_FAILED, message = "参数校验失败"),
            @ApiResponse(code = CommonResult.UNAUTHORIZED, message = "未认证"),
            @ApiResponse(code = CommonResult.FORBIDDEN, message = "未授权"),
            @ApiResponse(code = CommonResult.FAILED, message = "操作失败")})
    @ResponseBody
    @DeleteMapping("delete")
    public CommonResult delete(@RequestParam(value = "id", required = true) Long id) {
        try {
            if (service.delete(id)) {
                return new CommonResult().success("注销成功");
            } else {
                return new CommonResult().failed("注销失败");
            }
        } catch (Exception e) {
            return new CommonResult().failed(e.getMessage());
        }
    }

    @PostMapping("edit")
    @ApiOperation(value = "修改点位", notes = "修改点位")
    @ApiResponses({@ApiResponse(code = CommonResult.SUCCESS, message = "操作成功"),
            @ApiResponse(code = CommonResult.VALIDATE_FAILED, message = "参数校验失败"),
            @ApiResponse(code = CommonResult.UNAUTHORIZED, message = "未认证"),
            @ApiResponse(code = CommonResult.FORBIDDEN, message = "未授权"),
            @ApiResponse(code = CommonResult.FAILED, message = "操作失败")})
    @ResponseBody
    public CommonResult edit(@RequestBody MediaPointDTO dto) {
        MediaPoint temp = new MediaPoint();
        temp.setMedia_type_spec_id(dto.getMedia_type_specs_id());
        BeanUtils.copyProperties(dto, temp);
        boolean flag;
        // 查询修改的数据的新code是否存在status为0的数据, 存在即将status为0的数据的code改成修改的数据的原来的code
        LambdaQueryWrapper<MediaPoint> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MediaPoint::getStatus, 0).isNull(MediaPoint::getDeleted_at).eq(MediaPoint::getCode, dto.getCode());
        List<MediaPoint> mediaPoints = service.list(wrapper);
        if (CollUtil.isNotEmpty(mediaPoints) && mediaPoints.size()==1) {
            MediaPoint mediaPoint = mediaPoints.get(0);
            MediaPoint point = new MediaPoint();
            point.setCode(dto.getOld_code());
            point.setId(mediaPoint.getId());
            mediaPointMapper.updateById(point);
        }
        if (temp.getMedia_type_id() == 9) {
            flag = service.bindMarketPoint(temp);
        }else {
            flag = service.updateById(temp);
        }
        if (flag) {
            return new CommonResult().success("修改成功");
        }
        return new CommonResult().failed("修改失败");
    }

    @GetMapping("checkCode")
    @ApiOperation(value = "校验code唯一", notes = "校验code唯一")
    @ApiResponses({@ApiResponse(code = CommonResult.SUCCESS, message = "操作成功"),
            @ApiResponse(code = CommonResult.VALIDATE_FAILED, message = "参数校验失败"),
            @ApiResponse(code = CommonResult.UNAUTHORIZED, message = "未认证"),
            @ApiResponse(code = CommonResult.FORBIDDEN, message = "未授权"),
            @ApiResponse(code = CommonResult.FAILED, message = "操作失败")})
    @ResponseBody
    public CommonResult checkCode(@ApiParam(name = "code", value = "编号", required = true)
                                      @RequestParam(value = "code", required = false) String code,
                                  @ApiParam(name = "id", value = "修改时点位id", required = false)
                                    @RequestParam(value = "id", required = false) Long id){
        return new CommonResult().success(service.checkCode(code,id));
    }

    @GetMapping("checkABCode")
    @ApiOperation(value = "校验code是否在此市场点位中唯一", notes = "校验code是否在此市场点位中唯一")
    @ApiResponses({@ApiResponse(code = CommonResult.SUCCESS, message = "操作成功"),
            @ApiResponse(code = CommonResult.VALIDATE_FAILED, message = "参数校验失败"),
            @ApiResponse(code = CommonResult.UNAUTHORIZED, message = "未认证"),
            @ApiResponse(code = CommonResult.FORBIDDEN, message = "未授权"),
            @ApiResponse(code = CommonResult.FAILED, message = "操作失败")})
    @ResponseBody
    public CommonResult checkABCode(@ApiParam(name = "code", value = "编号", required = true)
                                  @RequestParam(value = "code", required = false) String code,
                                    @ApiParam(name = "id", value = "项目id", required = false)
                                    @RequestParam(value = "building_area_id", required = false) Long building_area_id,
                                  @ApiParam(name = "id", value = "修改时点位id", required = false)
                                  @RequestParam(value = "id", required = false) Long id){
        return new CommonResult().success(service.checkABCode(code, building_area_id, id));
    }

    /**
     * 导入数据
     * @param file
     * @return
     */
    @ApiOperation(value = "导入普通点位表", notes = "导入普通点位表")
    @ApiResponses({@ApiResponse(code = CommonResult.SUCCESS, message = "操作成功"),
            @ApiResponse(code = CommonResult.VALIDATE_FAILED, message = "参数校验失败"),
            @ApiResponse(code = CommonResult.UNAUTHORIZED, message = "未认证"),
            @ApiResponse(code = CommonResult.FORBIDDEN, message = "未授权"),
            @ApiResponse(code = CommonResult.FAILED, message = "操作失败")})
    @ResponseBody
    @PostMapping("import_common")
    public CommonResult importCommonExcel(@RequestParam("file") MultipartFile file, @ApiParam(name = "building_area_id", value = "项目id", required = false)
    @RequestParam(value = "building_area_id", required = false) Long building_area_id) {
        //if (bindingResult.hasErrors()) return new CommonResult().validateFailed(bindingResult);
        try {
            List<ImportCommonPointDTO> list = ExcelUtils.importExcel(file,0,1,ImportCommonPointDTO.class);
            List<MediaPointDTO> new_list = new ArrayList<>();
            if(CollectionUtils.isEmpty(list)){
                return new CommonResult().failed("文件内容为空，新增失败！");
            }
            for (ImportCommonPointDTO pointDTO:list){
                pointDTO.setBuilding_area_id(building_area_id);
                MediaPointDTO dto = new MediaPointDTO();
                BeanUtils.copyProperties(pointDTO, dto);
                new_list.add(dto);
            }

            if (service.saveList(new_list)) {
                return new CommonResult().success("新增成功");
            } else {
                return new CommonResult().failed("新增失败");
            }
        } catch (Exception e) {
            return new CommonResult().failed(e.getMessage());
        }
    }

    /**
     * 导入数据
     * @param file
     * @return
     */
    @ApiOperation(value = "导入ab点位表", notes = "导入ab点位表")
    @ApiResponses({@ApiResponse(code = CommonResult.SUCCESS, message = "操作成功"),
            @ApiResponse(code = CommonResult.VALIDATE_FAILED, message = "参数校验失败"),
            @ApiResponse(code = CommonResult.UNAUTHORIZED, message = "未认证"),
            @ApiResponse(code = CommonResult.FORBIDDEN, message = "未授权"),
            @ApiResponse(code = CommonResult.FAILED, message = "操作失败")})
    @ResponseBody
    @PostMapping("import_ab")
    public CommonResult importAbExcel(@RequestParam("file") MultipartFile file, @ApiParam(name = "building_area_id", value = "项目id", required = false)
    @RequestParam(value = "building_area_id", required = false) Long building_area_id) {
        try {
            List<ImportAbPointDTO> list = ExcelUtils.importExcel(file,1,1,ImportAbPointDTO.class);
            if(CollectionUtils.isEmpty(list)){
                return new CommonResult().failed("文件内容为空，新增失败！");
            }

            if (service.saveImportAbList(list,building_area_id)) {
                return new CommonResult().success("新增成功");
            } else {
                return new CommonResult().failed("新增失败");
            }
        } catch (Exception e) {
            return new CommonResult().failed(e.getMessage());
        }
    }
}
